<?php
class Comments extends Data_Item
{
    public $_commTableName = 'mod_scenic_comments';

    public function getComments($action,$tid,$limit=5,$offset=0){
        if($action == 'scenicspot'){
            $table = 'mod_scenic_spot';
        }else{return null;}

        $query = DB::select()
            ->from($this->_commTableName)
            ->where('targetId','=',$tid)
            ->limit($limit)
            ->offset($offset)->order_by('created','desc');

        $query = $query->execute();
        $data = array();
        foreach($query as $v){
            $tmp_icon = User_UserInfo::user_info($v['uid'])->current();
            $tmp_nickname = User_Account::user_account_info($v['uid'])->current();
            $v['nickname'] = $tmp_nickname['userName'];
            $v['icon'] = $tmp_icon['userIcon'];
            $v['created'] = date('Y.m.d',$v['created']);
            $data[] = $v;
        }
        return $data;
    }

    public static function getCommentsCounts($data){
        $user = user::currentUser();
        $uid = $user->getUserUid();
        $item = array();
        foreach($data as &$v){
            $rs = self::getCommentsCountsByTableId($v['id']);
            $v['comments'] = $rs;
            $item[] = $v;
        }
        return $item;
    }

    public static function getCommentsCountsByTableId($id,$uid=NULL){
        $query = DB::select(array(DB::expr('count(id)'),'counts'))
            ->from('mod_scenic_comments')
            ->where('targetId','=',$id);
        if($uid != NULL){
            $query = $query->where('uid','=',$uid);
        }
        return $query->execute()->get('counts');
    }

    public static function getActivityOrTrackComments($id,$type="track",$limit=20,$offset=0){
        $table = "mod_track_comments";
        $key = 'track_id';
        switch ($type){
            case 'track':
       		$mod_type="TRACK";
       		break;
            case 'activity':
       		$mod_type="ACTIVITY";
       		break;
            case 'ziying':
       		$mod_type="ZIYING";
       		break;
            default:
       		return array();      		
        }
        $query = DB::select()
            ->from($table)
            ->where($key,'=',$id)
            ->where('type','=',$mod_type)
        ->limit($limit)
        ->offset($offset)
        ->execute();
        $list = array();
        foreach($query as $v){
            $user = user::getUserFromUid(Arr::get($v,'uid'));
            $v['userName'] = $user->getUserName();
            $v['userIcon'] = $user->getUserIcon();
            $v['created'] = date('Y.m.d H:i:s',Arr::get($v,'created'));
            $list[] = $v;
        }
        return $list;
    }


    public function remove_comment($id){
        DB::delete($this->_commTableName)
            ->where('id','=',$id)
            ->execute();


    }


}
